#include "CPolygon.h"

CPolygon::CPolygon()
:Polygon(NULL),
NumVectors(0),
Min(99999,99999),
Max(-99999,-99999),
InsideOut( false )
{
	AddVector( 6 );
}

CPolygon::~CPolygon()
{
	if( Polygon ) delete []Polygon;
	Polygon = NULL;
	NumVectors = NULL;
}

void CPolygon::Render()
{
	//Vector2d vecPrevious, vecCurrent;
    //D3DXVECTOR3 vtxPrevious, vtxCurrent;

	glBindTexture( GL_TEXTURE_2D, 0 );
	glBegin( GL_LINE_LOOP );
	glColor4f( 1.0f, 1.0f, 1.0f, 1.0f );
 
	for( int i = 0; i < NumVectors; i++ )//float t = 0.0f; t < PI*2; t+= nextstep )
	{
		//glColor4f( float(i)/NumVectors , float(i)/NumVectors , float(i)/NumVectors , 1 );
		//float x = r * cosf( t ) + cx;
		//float y = r * sinf( t ) + cy;
		//glColor3f( 5*i , 5+i , 5/(i+1) );
		glVertex2f( Polygon[i].x, Polygon[i].y );
	}
	glEnd();

}

void CPolygon::AddVector( int count )
{
	Vector2d* temp = NULL;
	temp = new Vector2d[ NumVectors + count ];
	//existing data?
	if( Polygon )
	{
		//copy the old data into the new buffer
		memcpy( temp, Polygon, sizeof(Vector2d) );
		//release the old buffer
		delete []Polygon;
	}//end if polygon already existed
	
	//store pointer for new buffer
	Polygon = temp;
	NumVectors += count;

}

void CPolygon::SetBoundingBox()
{
	Vector2d min = Vector2d(99999,99999);
	Vector2d max = Vector2d(-99999,-99999);
	for( int i = 0; i < NumVectors; i++ )
	{
		if( Polygon[i].x < min.x )	{ min.x = Polygon[i].x; }
		if( Polygon[i].y < min.y )	{ min.y = Polygon[i].y; }
		if( Polygon[i].x > max.x )	{ max.x = Polygon[i].x; }
		if( Polygon[i].y > max.y )	{ max.y = Polygon[i].y; }
	}
	Max = max;
	Min = min;
}

bool CPolygon::InBoundingBox( CEntity* object )
{
	float cr    = object->GetCollisionRadius();
		//bminx = GetPosX() - cr;
		//bmaxx = GetPosX() + cr;
		//bminy = GetPosY() - cr;
		//bmaxy = GetPosY() + cr;
	if( InsideOut == false )
	{
		if( object->GetPosX() - cr >= Max.x ) { return false; } //player to the right, no collision
		if( object->GetPosX() + cr <= Min.x ) { return false; } //player to the left, no collision
		if( object->GetPosY() - cr >= Max.y ) { return false; } //player above, no collision
		if( object->GetPosY() + cr <= Min.y ) { return false; } //player below, no collision
		return true;
	}
	else
	{
		if( object->GetPosX() - cr >= Max.x ) { return true; } //player to the right, no collision
		if( object->GetPosX() + cr <= Min.x ) { return true; } //player to the left, no collision
		if( object->GetPosY() - cr >= Max.y ) { return true; } //player above, no collision
		if( object->GetPosY() + cr <= Min.y ) { return true; } //player below, no collision
		return true;
	}

}